package com.hj.chartdemo.view

import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.github.mikephil.charting.data.Entry
import com.hj.chartdemo.R
import com.hj.chartdemo.chart.BarChartManagger
import com.hj.chartdemo.chart.LineChartManagger
import com.hj.chartdemo.databinding.ActivityChartBinding
import com.hj.chartdemo.utils.BaseActivity
import com.hj.chartdemo.viewmodel.ChartActivityViewModel
import java.util.ArrayList


class ChartActivity : BaseActivity<ActivityChartBinding>() {

    override fun initContentView(): Int {
        return R.layout.activity_chart
    }

    override fun initViewModel(): ViewModel? {
        return ViewModelProvider(this).get(ChartActivityViewModel::class.java)
    }

    override fun initView() {
        LineChartManagger.getInstance().init(this, binding?.lineChart)
        BarChartManagger.getInstance().init(this, binding?.barChart)
    }

    override fun initData() {
        binding.viewModel?.chartData?.observe(this, Observer { data ->

            var ztDatas = ArrayList<ArrayList<Entry>>()
            val values = ArrayList<Entry>()
            var xlab = ArrayList<String>()
            var index = 1

            data.datas.forEach {
                values.add(Entry(index.toFloat(), it.value.toFloat(), it.label))
                xlab.add(it.label)
                index++
            }
            ztDatas.add(values)

            LineChartManagger.getInstance().loadData(this, binding?.lineChart, ztDatas, ArrayList<String>(), data.colors, xlab, data.showLegend, "")

            BarChartManagger.getInstance().loadData(this, binding?.barChart, ztDatas, ArrayList<String>(), data.colors, xlab, data.showLegend)

            binding.chart.setData(data)
        })

        binding.viewModel?.pieChartData?.observe(this, Observer { data ->
            binding.pieChart.setData(data)
        })
    }
}
